import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class ImageCode extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置图片十秒刷新一次
        resp.setHeader("refresh","10");

        //在内存中创建一个图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        //设置图片背景颜色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,80,20);

        graphics.setColor(Color.pink);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(num(),0,20);

        //告诉浏览器，这个请求用图片方式打开
        resp.setContentType("image/jpeg");
        //不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        ImageIO.write(image,"jpg",resp.getOutputStream());

    }

    public static String num(){
        int i = new Random().nextInt(9999);
        return String.valueOf(i);
    }

    public static void main(String[] args) {
        System.out.println(num());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
